import logging
from flask import jsonify
from elasticsearch import Elasticsearch


success = 200
internal_error = 500
data_missing = 101     # 数据库内无相关数据


class SearchAPI(object):
    def __init__(self):
        pass

    @classmethod
    def Searchapi(cls, request):
        """
        搜索接口，调用ES查找文件名称，并使其关键词并高亮
        keywords: 关键字
        """
        logging.debug("working on Search_api")
        msg = "获取列表成功"
        code = success
        keywords = request.values.get('keywords')
        if keywords is None or len(keywords) == 0:
            keywords = ""
        es = Elasticsearch(['119.91.216.229'], port=9200)  # 连接本地9200端口
        # 关键字符
        # 标准化输出，可直接套入flask框架中使用
        query = {'query': {'match': {'name': keywords}}}
        result = es.search(index='records', doc_type='doc', body=query)
        # logging.debug(f"result:{result}")

        file_data = []
        if result['hits']['total'] == 0:
            logging.debug("No matching data")
            code = data_missing
            msg = "无匹配结果，请更换搜索关键字！"
        else:
            hits = result['hits']['hits']
            for i in range(0, len(hits)):
                data = {}
                # 匹配名称内字符，为其关键词前后加<em></em>
                individual_name = hits[i]['_source']['name']
                # 当匹配到关键字符，对该名称做修改
                if individual_name.find(keywords):
                    # 两个方法，一个是在里面匹配后替换，直接用keyword替换即可
                    str = "<em>" + individual_name[
                                   individual_name.find(keywords):individual_name.find(keywords) + len(keywords)] + "</em>"
                    individual_name = individual_name.replace(keywords, str)
                data['name'] = individual_name
                data['id'] = hits[i]['_source']['id']
                data['label'] = hits[i]['_source']['label']
                data['rank'] = hits[i]['_source']['rank']

                file_data.append(data)
        resp = {
            "code": code,
            "msg": msg,
            "data": file_data
        }

        return jsonify(resp)
